﻿using System;
using System.Windows.Controls;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Concurrency;
using Caliburn.Micro;
using PicturePortfolio.ServiceReference;
namespace PicturePortfolio.Silverlight.ViewModels
{
    public class UploadPhotoViewModel:Screen
    {
        private PhotoServiceClient _photoService;
        public UploadPhotoViewModel(PhotoServiceClient photoService)
        {
            this.IsBusy = false;
            _photoService = photoService;
            this.StatusMessage = string.Empty;
            
            this.PhotosToUpload = new ObservableCollection<IndividualThumbnailViewModel>();
        }

        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);
            this.LoadCategories();
        }
        private void LoadCategories()
        {
            try
            {

                var func = Observable.FromEvent<GetCategoriesCompletedEventArgs>(_photoService, "GetCategoriesCompleted")
                    .ObserveOn(Scheduler.ThreadPool);
                _photoService.GetCategoriesAsync();

                func.ObserveOn(Scheduler.Dispatcher)
                    .Select(result => result.EventArgs.Result)
                    .Subscribe(s => this.Categories = s.ToList());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        private string _statusMessage;
        public string StatusMessage
        {
            get { return _statusMessage; }
            private set 
            {
                _statusMessage = value;
                NotifyOfPropertyChange(() => StatusMessage);
            }
        }

        private List<Category> _categories;
        public List<Category> Categories
        {
            get { return _categories; }
            set
            {
                _categories = value;
                NotifyOfPropertyChange(() => Categories);
            }
        }
        private ObservableCollection<IndividualThumbnailViewModel> _photosToUpload;
        public ObservableCollection<IndividualThumbnailViewModel> PhotosToUpload
        {
            get { return _photosToUpload; }
            set
            {
                _photosToUpload = value;
            }
        }

        public Category SelectedCategory { get; set; }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                NotifyOfPropertyChange(() => IsBusy);
            }
        }
        public void CategorySelectionChanged(object selectedItem)
        {
            this.SelectedCategory = selectedItem as Category;
        }
        public void BrowseButtonClicked()
        {
            this.StatusMessage = string.Empty;
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "jpg(*.jpg)|*.jpg|jpeg(*.jpeg)|*.jpeg";
            dlg.Multiselect = true;
            if (dlg.ShowDialog() == true)
            {
                
                foreach (FileInfo filInfo in dlg.Files)
                {
                    FileStream reader = filInfo.OpenRead();
                    byte[] byteArray = new byte[reader.Length];
                    reader.Read(byteArray, 0, Convert.ToInt32(reader.Length));
                    this.AddToCollection(byteArray,filInfo.Name);
                }
            }
        }
        private void AddToCollection(byte[] imageInArray, string name)
        {
            Photo photo = new Photo();
            photo.ImageFile = imageInArray;
            photo.ImageThumbNail = imageInArray;
            photo.Name = name;
            photo.PublicComments = new List<PublicComment>();
            photo.PhotoCategory = this.SelectedCategory;

            IndividualThumbnailViewModel thumbNailPhoto = new IndividualThumbnailViewModel(photo);
            this.PhotosToUpload.Add(thumbNailPhoto);
        }
        private void SavePhotos(List<Photo> photos)
        {
            _photoService.SavePhotosAsync(photos, null);
        }

        public void Upload()
        {
            this.IsBusy = true;
            List<Photo> photos = new List<Photo>();
            //System.Threading.Thread.Sleep(1000);
            _photoService.SavePhotoCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_photoService_SavePhotoCompleted);
            foreach (IndividualThumbnailViewModel thumbNail in _photosToUpload)
            {
                //photos.Add(thumbNail.Photo);
                _photoService.SavePhotoAsync(thumbNail.Photo);
            }
            //this.SavePhotos(photos);
            this.PhotosToUpload.Clear();
            this.IsBusy = false;
            this.StatusMessage = "Upload Completed";
            Message.EventAggregationProvider.EventAggregator.Publish<Message.RefreshPhotoPreviewMessage>(new Message.RefreshPhotoPreviewMessage(null) { Sender=this,SelectedCategory=null });
        }

        void _photoService_SavePhotoCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                string err = e.Error.Message;
            }
        }

    }
    
}
